/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.htrelatedevice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.hontu.issued.request.DeviceInfoQueryRequest;
import vip.xiaonuo.hontu.issued.request.PageQueryRequest;
import vip.xiaonuo.hontu.issued.response.DeviceInfo;
import vip.xiaonuo.hontu.issued.response.DeviceInfoQueryResponse;
import vip.xiaonuo.hontu.issued.response.DeviceListQueryResponse;
import vip.xiaonuo.hontu.issued.util.HT_DEVICE_POST;
import vip.xiaonuo.hontu.issued.util.HongTuRequestUrl;
import vip.xiaonuo.modular.htrelatedevice.entity.HtRelateDevice;
import vip.xiaonuo.modular.htrelatedevice.enums.HtRelateDeviceExceptionEnum;
import vip.xiaonuo.modular.htrelatedevice.mapper.HtRelateDeviceMapper;
import vip.xiaonuo.modular.htrelatedevice.param.HtRelateDeviceParam;
import vip.xiaonuo.modular.htrelatedevice.service.HtRelateDeviceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 平台下属设备service接口实现类
 *
 * @author Joe
 * @date 2023-05-25 13:44:05
 */
@Service
public class HtRelateDeviceServiceImpl extends ServiceImpl<HtRelateDeviceMapper, HtRelateDevice> implements HtRelateDeviceService {

    @Resource
    private DeviceBaseService deviceService;

    @Override
    public PageResult<HtRelateDevice> page(HtRelateDeviceParam htRelateDeviceParam) {
        QueryWrapper<HtRelateDevice> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(htRelateDeviceParam)) {

            // 根据device_base_id 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getDeviceBaseId())) {
                queryWrapper.lambda().eq(HtRelateDevice::getDeviceBaseId, htRelateDeviceParam.getDeviceBaseId());
            }
            // 根据uuid 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getUuid())) {
                queryWrapper.lambda().eq(HtRelateDevice::getUuid, htRelateDeviceParam.getUuid());
            }
            // 根据设备位置 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getLocation())) {
                queryWrapper.lambda().eq(HtRelateDevice::getLocation, htRelateDeviceParam.getLocation());
            }
            // 根据名称 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getName())) {
                queryWrapper.lambda().eq(HtRelateDevice::getName, htRelateDeviceParam.getName());
            }
            // 根据设备类型 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getDeviceType())) {
                queryWrapper.lambda().eq(HtRelateDevice::getDeviceType, htRelateDeviceParam.getDeviceType());
            }
            // 根据mac地址 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getMac())) {
                queryWrapper.lambda().eq(HtRelateDevice::getMac, htRelateDeviceParam.getMac());
            }
            // 根据IP地址 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getIpAddress())) {
                queryWrapper.lambda().eq(HtRelateDevice::getIpAddress, htRelateDeviceParam.getIpAddress());
            }
            // 根据设备状态 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getStatus())) {
                queryWrapper.lambda().eq(HtRelateDevice::getStatus, htRelateDeviceParam.getStatus());
            }
            // 根据设备模式 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getDeviceMode())) {
                queryWrapper.lambda().eq(HtRelateDevice::getDeviceMode, htRelateDeviceParam.getDeviceMode());
            }
            // 根据当前版本 查询
            if (ObjectUtil.isNotEmpty(htRelateDeviceParam.getCurrentVersion())) {
                queryWrapper.lambda().eq(HtRelateDevice::getCurrentVersion, htRelateDeviceParam.getCurrentVersion());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<HtRelateDevice> list(HtRelateDeviceParam htRelateDeviceParam) {
        return this.list();
    }

    @Override
    public void add(HtRelateDeviceParam htRelateDeviceParam) {
        HtRelateDevice htRelateDevice = new HtRelateDevice();
        BeanUtil.copyProperties(htRelateDeviceParam, htRelateDevice);
        this.save(htRelateDevice);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(HtRelateDeviceParam htRelateDeviceParam) {
        this.removeById(htRelateDeviceParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(HtRelateDeviceParam htRelateDeviceParam) {
        HtRelateDevice htRelateDevice = this.queryHtRelateDevice(htRelateDeviceParam);
        BeanUtil.copyProperties(htRelateDeviceParam, htRelateDevice);
        this.updateById(htRelateDevice);
    }

    @Override
    public HtRelateDevice detail(HtRelateDeviceParam htRelateDeviceParam) {
        return this.queryHtRelateDevice(htRelateDeviceParam);
    }

    @Override
    public void syncBatch(HtRelateDeviceParam htRelateDeviceParam) {
        DeviceBase deviceBase = deviceService.getById(htRelateDeviceParam.getDeviceBaseId());
        if(deviceBase == null || ObjectUtil.notEqual(deviceBase.getDeviceType(),"10")  ){
            throw new ServiceException(500,"该设备平台下没有设备或无需获取设备");
        }else if( ObjectUtil.notEqual(deviceBase.getDeviceState(),"1") ){
            throw new ServiceException(500,"设备不在线");
        }else {
            this.doSyncBatch(deviceBase);
        }
    }

    private void doSyncBatch(DeviceBase deviceBase){
        List<DeviceInfo> devices = new ArrayList<>();
        PageQueryRequest request = new PageQueryRequest();
        int total = -1;
        try {
            while(total!= devices.size()){
                DeviceListQueryResponse response = HT_DEVICE_POST.postJson(HongTuRequestUrl.POST_DEVICE_LIST_QUERY, deviceBase.getCabinetIp(),deviceBase.getCabinetPort(), request ,DeviceListQueryResponse.class);
                if(response.getCode() == 0) { // 请求成功
                    devices.addAll(response.getData().getList());
                    total = response.getData().getTotal();
                    request.setPageNum(request.getPageNum()+1);
                }else{
                    throw new ServiceException(response.getCode(),response.getMsg());
                }
            }

            List<HtRelateDevice> toBeSave = new ArrayList<>();
            List<String> deviceUUIDs = new ArrayList<>();
            for(DeviceInfo deviceInfo : devices){
                deviceUUIDs.add(deviceInfo.getUuid());
                HtRelateDevice device = this.getOne(new LambdaQueryWrapper<HtRelateDevice>()
                        .eq(HtRelateDevice :: getDeviceBaseId , deviceBase.getId())
                        .eq(HtRelateDevice :: getUuid , deviceInfo.getUuid()));
                if(ObjectUtil.isNull(device)){
                    device = new HtRelateDevice();
                    device.setDeviceBaseId(deviceBase.getId());
                }
                BeanUtil.copyProperties(deviceInfo, device);
                toBeSave.add(device);
            }

            this.remove(new LambdaQueryWrapper<HtRelateDevice>()
                    .eq(HtRelateDevice :: getDeviceBaseId , deviceBase.getId())
                    .notIn(HtRelateDevice :: getUuid , deviceUUIDs));
            this.saveOrUpdateBatch(toBeSave);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void syncOne(HtRelateDeviceParam htRelateDeviceParam) {
        DeviceBase deviceBase = deviceService.getById(htRelateDeviceParam.getDeviceBaseId());
        if(deviceBase == null || ObjectUtil.notEqual(deviceBase.getDeviceType(),"10")  ){
            this.remove(new LambdaQueryWrapper<HtRelateDevice>().eq(HtRelateDevice :: getDeviceBaseId , deviceBase.getId()));
            throw new ServiceException(500,"该设备平台下没有设备或无需获取设备");
        }else if( ObjectUtil.notEqual(deviceBase.getDeviceState(),"1") ){
            throw new ServiceException(500,"设备不在线");
        }else {
            HtRelateDevice device = this.getById(htRelateDeviceParam.getId());
            if(ObjectUtil.isNull(device)){
                throw new ServiceException(500,"该设备已删除");
            }
            this.doSyncOne(deviceBase,device);
        }
    }

    private void doSyncOne(DeviceBase deviceBase, HtRelateDevice device) {
        DeviceInfoQueryRequest request = new DeviceInfoQueryRequest();
        request.setUuid(device.getUuid());
        try {
            DeviceInfoQueryResponse response = HT_DEVICE_POST.postJson(HongTuRequestUrl.POST_DEVICE_INFO_QUERY, deviceBase.getCabinetIp(),deviceBase.getCabinetPort() , request, DeviceInfoQueryResponse.class);
            if(response.getCode() == 0){
                BeanUtil.copyProperties(response.getData() , device );
                this.updateById(device);
            }else if(response.getCode() == 102013){// 设备不存在
                this.removeById(device.getId());
                throw new ServiceException(response.getCode(),"设备不存在，本地已删除");
            }else{
                throw new ServiceException(response.getCode(),response.getMsg());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取平台下属设备
     *
     * @author Joe
     * @date 2023-05-25 13:44:05
     */
    private HtRelateDevice queryHtRelateDevice(HtRelateDeviceParam htRelateDeviceParam) {
        HtRelateDevice htRelateDevice = this.getById(htRelateDeviceParam.getId());
        if (ObjectUtil.isNull(htRelateDevice)) {
            throw new ServiceException(HtRelateDeviceExceptionEnum.NOT_EXIST);
        }
        return htRelateDevice;
    }
}
